import { apiConfig } from '../../shared/services/api-config'
import type { ApiResponse } from '../../../types/api'
import type { CharacterProfile } from './book-role-service' 

// 小说大纲请求参数接口
export interface NovelOutlineRequest {
  modelId: number
  title?: string
  userPrompt: string
  wordCount: number // 改为总字数，单位万字
  genre?: string // 支持逗号分隔的多选题材
  systemPromptId?: number
  systemPrompt?: string
  bookId?: number // 书籍ID，用于关联到现有书籍
  chapterCount?: number // 章节数量，用于生成章节规划
  abortSignal?: string // 终止信号，用于终止流式生成
}

// 章节大纲接口
export interface ChapterOutline {
  chapterNumber: number
  title: string
  summary: string
  beginChapterNum?: number
  endChapterNum?: number
  wordCount?: number
  watch?: string
  storyLine?: string
  emotionalLine?: string
}

// 小说大纲响应接口
export interface NovelPlan {
  mainPlot: string
  subPlots: string[]
  chapterOutlines: ChapterOutline[]
  characterProfiles: CharacterProfile[]
}

// 小说大纲实体接口（匹配后端NovelOutline实体）
export interface NovelOutline {
  id?: number
  bookId: number
  mainPlot: string
  characterProfiles: string // JSON字符串
  subPlots: string // JSON字符串
  chapterPlanning: string // JSON字符串
  taskId?: string
  status?: number
  errorMessage?: string
  createTime?: string
  updateTime?: string
}

// 异步任务接口
export interface AsyncTask {
  id: string
  taskType: string
  status: string
  progress: number
  message?: string
  params?: string
  result?: string
  createTime: string
  updateTime: string
  startTime?: string
  endTime?: string
}

// 小说大纲更新请求接口
export interface OutlineUpdateRequest {
  id?: number // 大纲id，更新时使用
  bookId: number
  version?: number // 更新时使用
  outlineDetails: string
  chapterPlanning: string
  subPlots?: string // 支线规划
  isActive?: number // 启用状态：0-禁用，1-启用
  remark?: string // 备注信息，标题作用
}

// 小说大纲API
export const novelOutlineApi = {
  
  // 根据书籍ID查询大纲详情
  async getNovelOutlineByBookId(bookId: number): Promise<ApiResponse<NovelOutline>> {
    const response = await apiConfig.getAxiosInstance().get(`/novel/outline/book/${bookId}`)
    return response.data
  },
  
  // 获取书籍所有版本的大纲列表
  async getOutlineListByBookId(bookId: number): Promise<ApiResponse<NovelOutline[]>> {
    const response = await apiConfig.getAxiosInstance().get(`/novel/outline/list/${bookId}`)
    return response.data
  },
  
  // 获取书籍最新版本的大纲详情
  async getLatestOutlineByBookId(bookId: number): Promise<ApiResponse<NovelOutline>> {
    const response = await apiConfig.getAxiosInstance().get(`/novel/outline/${bookId}/new`)
    return response.data
  },
  
  // 根据书籍ID和版本号查询大纲详情
  async getOutlineByBookVersion(bookId: number, version: number): Promise<ApiResponse<NovelOutline>> {
    const response = await apiConfig.getAxiosInstance().get(`/novel/outline/${bookId}/${version}`)
    return response.data
  },

  // 查询书籍人设
  async getCharacterProfilesByBookId(bookId: number): Promise<ApiResponse<CharacterProfile[]>> {
    const response = await apiConfig.getAxiosInstance().get(`/novel/character-profile/book/${bookId}`)
    return response.data
  },
  
  // 添加人设
  async addCharacterProfile(data: Partial<CharacterProfile>): Promise<ApiResponse<CharacterProfile>> {
    const response = await apiConfig.getAxiosInstance().post('/book-roles', data)
    return response.data
  },
  
  // 更新人设
  async updateCharacterProfile(data: Partial<CharacterProfile>): Promise<ApiResponse<CharacterProfile[]>> {
    const response = await apiConfig.getAxiosInstance().put('/book-roles', data)
    return response.data
  },
  
  // 删除人设
  async deleteCharacterProfile(bookId: number, version: number): Promise<ApiResponse<any>> {
    const response = await apiConfig.getAxiosInstance().delete(`/book-roles/${bookId}/${version}`)
    return response.data
  },
  
  // 删除大纲
  async deleteOutline(bookId: number, version: number): Promise<ApiResponse<boolean>> {
    const response = await apiConfig.getAxiosInstance().delete(`/novel/outline/${bookId}/${version}`)
    return response.data
  },
  
  // 重新生成大纲
  async regenerateOutline(bookId: number, request: NovelOutlineRequest): Promise<ApiResponse<string>> {
    const response = await apiConfig.getAxiosInstance().post(`/novel/outline/book/${bookId}/regenerate`, request)
    return response.data
  },
  
  // 更新大纲
  async updateOutline(request: OutlineUpdateRequest): Promise<ApiResponse<boolean>> {
    const response = await apiConfig.getAxiosInstance().put('/novel/outline/update', request)
    return response.data
  },
  
  // 归档大纲
  async archiveOutline(request: OutlineUpdateRequest): Promise<ApiResponse<number>> {
    const response = await apiConfig.getAxiosInstance().post('/novel/outline/archive', request)
    return response.data
  },
  
  // 保存或更新大纲
  async saveOrUpdateOutline(request: OutlineUpdateRequest): Promise<ApiResponse<NovelOutline>> {
    const response = await apiConfig.getAxiosInstance().post('/novel/outline/saveOrUpdate', request)
    return response.data
  },
  
  // 生成小说大纲（同步，保留原有方法）
  async generateOutline(request: NovelOutlineRequest): Promise<NovelPlan> {
    const response = await apiConfig.getAxiosInstance().post('/novel/outline/generate', request)
    return response.data.data
  },
  
  // 生成大纲（流式）
  async generateOutlineStream(request: NovelOutlineRequest): Promise<any> {
    // 构建请求体，符合StreamGenerationRequest格式
    const requestBody = {
      modelId: request.modelId,
      systemPromptId: request.systemPromptId,
      userPrompt: request.userPrompt,
      bookId: request.bookId,
      business: '大纲生成',
      abortSignal: request.abortSignal
    };
    
    // 构建请求头
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'Accept': 'text/plain;charset=UTF-8'
    }
    
    // 添加Authorization头
    const token = await import('../../shared/services/api-config').then(m => m.ApiConfig.getToken());
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    
    // 使用fetch API调用通用流式接口
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/common/stream/generate`, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(requestBody)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return response;
  },
  
  // 生成章节规划（流式）
  async generateChaptersStream(request: NovelOutlineRequest): Promise<any> {
    // 构建请求体，符合StreamGenerationRequest格式
    const requestBody = {
      modelId: request.modelId,
      systemPromptId: request.systemPromptId,
      userPrompt: request.userPrompt,
      bookId: request.bookId,
      business: '章节规划生成',
      abortSignal: request.abortSignal
    };
    
    // 构建请求头
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'Accept': 'text/plain;charset=UTF-8'
    }
    
    // 添加Authorization头
    const token = await import('../../shared/services/api-config').then(m => m.ApiConfig.getToken());
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    
    // 使用fetch API调用通用流式接口
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/common/stream/generate`, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(requestBody)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return response;
  },
  
  // 生成支线设定（流式）
  async generateSidelinesStream(request: NovelOutlineRequest): Promise<any> {
    // 构建请求体，符合StreamGenerationRequest格式
    const requestBody = {
      modelId: request.modelId,
      systemPromptId: request.systemPromptId,
      userPrompt: request.userPrompt,
      bookId: request.bookId,
      business: '支线设定生成',
      abortSignal: request.abortSignal
    };
    
    // 构建请求头
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'Accept': 'text/plain;charset=UTF-8'
    }
    
    // 添加Authorization头
    const token = await import('../../shared/services/api-config').then(m => m.ApiConfig.getToken());
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    
    // 使用fetch API调用通用流式接口
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/common/stream/generate`, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(requestBody)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return response;
  }
}